<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2019-04-02
 * Time: 13:03
 */

namespace App\HttpController\Api\User;

use App\HttpController\Api\Common\Helpers;
use App\Model\User\UserModel;
use EasySwoole\Http\Message\Status;
use EasySwoole\HttpAnnotation\AnnotationTag\Param;
use App\Model\System\ConfigModel;


class Auth extends UserBase
{
    protected $whiteList = ['login', 'register','test'];



    /**
     * login
     * @Param(name="userAccount", alias="用户名", required="")
     * @Param(name="userPassword", alias="密码", required="")
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * @author Tioncico
     * Time: 15:06
     */
    function login()
    {
        $param = $this->request()->getRequestParam();
        $userModel = new UserModel();
        $userModel->userAccount = $param['userAccount'];
        $userModel->userPassword = md5($param['userPassword']);
        if ($userInfo = $userModel->login()) {
            if($userInfo->status == '0'){
                $this->writeJson(Status::CODE_FORBIDDEN, '', '用户已拉黑');
            }else{
                //登录成功
                $sessionHash = md5(time() . $userInfo->userAccount);
                // 登录状态存redis
                $redis=\EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
                $redis->set($sessionHash,$userInfo->userId,3600*24);
                //回收对象
                \EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redis);
                $rs = $userInfo->toArray();
                $rs['userSession'] = $sessionHash;
                $userModel->updateSession($sessionHash);
                $this->response()->setCookie('userSession', $sessionHash, time() + 3600, '/');
                $this->writeJson(Status::CODE_OK, $rs);
            }
        } else {
            $this->writeJson(Status::CODE_BAD_REQUEST, '', '用户不存在');
        }
    }

    function logout()
    {
        $sessionKey = $this->request()->getRequestParam('userSession');
        if (empty($sessionKey)) {
            $sessionKey = $this->request()->getCookieParams('userSession');
        }
        if (empty($sessionKey)) {
            $this->writeJson(Status::CODE_UNAUTHORIZED, '', '尚未登入');
            return false;
        }
        $result = $this->getWho()->logout();
        if ($result) {
            $this->writeJson(Status::CODE_OK, '', "登出成功");
        } else {
            $this->writeJson(Status::CODE_UNAUTHORIZED, '', 'fail');
        }
    }

    function getInfo()
    {
        $this->writeJson(200, $this->getWho(), 'success');
    }

}
